<template>
  <div id="BusinessManagement">
    <vHeadSpace/>
    <div class="outcontainer">
      <vAsideSpace/>
      <el-main class="main">
        <el-card>
          <el-row>
            <el-col>
              <div>
                <h3 style="float: left; margin-top: -5px; font-weight: bold">业务列表</h3>
                <el-button type="primary" style="float: right; margin-bottom: 20px" @click="showAddBusinessDialog">
                  添加业务
                </el-button>

              </div>

              <el-table
                  :data="businessList"
                  style="width: 100%;margin-bottom: 20px;"
                  row-key="id"
                  border
                  lazy
                  :load="load"
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                <el-table-column
                    label="名称">
                  <template slot-scope="scope">
                    <!--                    <span style="line-height: 32px;"><i class="el-icon-setting" style="font-size: 30px;"></i></span>-->
                    <!--                    <span class="el-icon-setting" style="font-size: 20px;"></span>-->
                    {{ scope.row.name }}
                  </template>
                </el-table-column>
                <el-table-column
                    prop="type"
                    label="类型">
                </el-table-column>
                <el-table-column
                    label="操作">
                  <template slot-scope="scope">
                    <el-button type="primary" size="mini" v-if="scope.row.type === '业务'"
                               @click="showDialogAddHost(scope.row)">添加设备
                    </el-button>
                    <el-button type="primary" size="mini" v-if="scope.row.type === '业务'"
                               @click="showDialogAddDatabase(scope.row)">添加数据库
                    </el-button>
                    <!--                    <el-button type="info" size="mini" v-if="scope.row.type === '业务'">编辑</el-button>-->
                    <el-button type="danger" size="mini" @click="deleteItem(scope.row)">移除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-card>
      </el-main>
      <!--      添加业务对话框-->
      <el-dialog
          title="添加业务"
          :visible.sync="addBusinessDialog"
          width="30%"
          @close="closeAddBusinessDialog"
      >
        <el-form :model="addBusinessForm" :rules="addBusinessFormRules" ref="addBusinessFormRef">
          <el-form-item label="业务名称" prop="name">
            <el-input v-model="addBusinessForm.name" placeholder="业务名称长度不得超过40"></el-input>
          </el-form-item>
          <div>请选择设备和数据库</div>
          <div style="overflow: auto;height: 200px;margin-top: 10px">
            <el-tree :data="hostsList" :props="treeProps"
                     show-checkbox node-key="id"
                     :default-checked-keys="defKeysForHost" ref="treeRefForHost"></el-tree>
            <el-tree :data="databaseList" :props="treeProps"
                     show-checkbox node-key="id"
                     :default-checked-keys="defKeysForDatabase" ref="treeRefForDatabase"></el-tree>
          </div>

        </el-form>
        <span slot="footer">
        <el-button @click="closeAddBusinessDialog">取 消</el-button>
        <el-button type="primary" @click="addBusiness">确 定</el-button>
        </span>
      </el-dialog>
      <!--      添加设备对话框-->
      <el-dialog
          custom-class="tree-dialog-settings"
          title="添加设备"
          width="30%"
          :modal-append-to-body="false"
          :lock-scroll="false"
          :visible.sync="dialogAddHostVisible"
          @close="closeAddHostDialog"
      >
        <el-input
            placeholder="输入查找主机名(区分大小写)"
            v-model="filterText"
            style="margin-top: 10px"
            size="small">
        </el-input>
        <div style="overflow: auto;height: 300px;margin-top: 10px">
          <el-tree :data="hostsList" :props="treeProps"
                   show-checkbox node-key="id"
                   :default-checked-keys="defKeysForHost"
                   :filter-node-method="filterNode"
                   ref="treeRefForHost">
          </el-tree>
        </div>
        <span slot="footer">
        <el-button @click="closeAddHostDialog">取 消</el-button>
        <el-button type="primary" @click="addHost">确 定</el-button>
        </span>
      </el-dialog>
      <!--      添加数据库对话框-->
      <el-dialog
          custom-class="tree-dialog-settings"
          title="添加数据库"
          :modal-append-to-body="false"
          :lock-scroll="false"
          :visible.sync="dialogAddDatabaseVisible"
          @close="closeAddDatabaseDialog"
      >
        <el-input
            placeholder="输入查找数据库名(区分大小写)"
            v-model="filterText"
            style="margin-top: 10px"
            size="small">
        </el-input>
        <div style="overflow: auto;height: 300px;margin-top: 10px">
          <el-tree :data="databaseList" :props="treeProps"
                   show-checkbox node-key="id"
                   :default-checked-keys="defKeysForDatabase"
                   :filter-node-method="filterNode"
                   ref="treeRefForDatabase">
          </el-tree>
        </div>
        <span slot="footer">
        <el-button @click="closeAddDatabaseDialog">取 消</el-button>
        <el-button type="primary" @click="addDatabase">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <vFootSpace/>

  </div>
</template>
<script>
import axios from 'axios'

export default {
  name: 'BusinessManagement',
  inject: ['reload'],
  watch: {
    filterText(val) {
      this.$refs.treeRefForHost.filter(val);
      this.$refs.treeRefForDatabase.filter(val);
    }
  },
  data() {
    // 检验业务名称的规则
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error('业务名称不能为空'));
      } else if (value.length > 40) {
        callback(new Error('业务名称长度不能超过 40 '));
      } else {
        callback();
      }
    };

    return {
      addBusinessDialog: false,
      dialogAddHostVisible: false,
      dialogAddDatabaseVisible: false,
      filterText: '',
      addBusinessForm: {
        name: '',
        hosts: [],
        databases: []
      },
      addBusinessFormRules: {
        name: [
          {validator: validatePass, trigger: 'blur'},
          {pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9]{1,40}$/,message: '业务名称不能包含空格或特殊字符', trigger: 'blur'}
        ],
      },
      hostsList: [],
      databaseList: [],
      treeProps: {
        label: 'name',
        children: 'children'
      },
      defKeysForHost: [],
      defKeysForDatabase: [],
      businessList: [],
      children: [],
      clickBusinessId: 0
    }
  },
  mounted() {
    this.getAllBusiness()
  },
  methods: {
    async getAllBusiness() {
      const {data: res} = await this.$axios.post('/business/get_all_business.action')
      console.log(res)
      this.businessList = res.content.result
      //  添加数组，接收设备、数据库相关数据
      this.businessList.forEach(function (item) {
        item['children'] = []
      })
      console.log(this.businessList)
    },
    async getAllHosts() {
      const {data: res} = await this.$axios.post('/business/get_all_hosts.action')
      console.log(res)
      this.hostsList = res.content.result
    },
    async getAllDatabases() {
      const {data: res} = await this.$axios.post('/business/get_all_databases.action')
      console.log(res)
      this.databaseList = res.content.result
    },
    addBusiness() {
      // 删除 0 （为了展示树形结构，特意加上的 0）
      const hostKeys = [
        ...this.$refs.treeRefForHost.getCheckedKeys().filter(item => item !== 0)
        // ...this.$refs.treeRefForHost.getHalfCheckedKeys()
      ]
      const databaseKeys = [
        ...this.$refs.treeRefForDatabase.getCheckedKeys().filter(item => item !== 0)
      ]
      this.addBusinessForm.hosts = hostKeys
      this.addBusinessForm.databases = databaseKeys
      this.$refs.addBusinessFormRef.validate(async valid => {
        if (valid) {
          if (this.addBusinessForm.hosts.length === 0) {
            return this.$message.info("请选择主机")
          }
          const {data: res} = await this.$axios.post('/business/add_business.action', this.addBusinessForm)
          console.log(res)
          if (res.content.result > 0) {
            this.$message.success("添加业务成功")
            this.addBusinessDialog = false
          }
          await this.getAllBusiness()
        }
      })
    },
    closeAddBusinessDialog() {
      this.hostsList = []
      this.databaseList = []
      this.defKeysForHost = []
      this.defKeysForDatabase = []
      this.$refs.addBusinessFormRef.resetFields()
      this.addBusinessDialog = false
    },
    show(info) {
      console.log(info)
    },
    filterNode(value, data) {
      console.log(value, data)
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    async showDialogAddHost(business) {
      this.dialogAddHostVisible = true
      await this.getAllHosts()
      const {data: res} = await this.$axios.post('/business/get_business_info_host_by_id.action', {id: business.id})
      console.log(res)
      let temp = []
      // 设置默认选中
      res.content.result.forEach((item) => {
        temp.push(item.real_id)
      })
      // 设置禁用
      this.hostsList[0].children.forEach((item) => {
        if (temp.indexOf(item.id) !== -1) {
          item['disabled'] = true
        }
      })
      console.log(this.hostsList)
      this.defKeysForHost = temp
      // 点击添加后，赋值（方便addHost传参数）
      this.clickBusinessId = business.id
    },
    // 关闭 添加设备 dialog
    closeAddHostDialog() {
      this.hostsList = []
      this.defKeysForHost = []
      this.dialogAddHostVisible = false
    },
    closeAddDatabaseDialog() {
      this.databaseList = []
      this.defKeysForDatabase = []
      this.dialogAddDatabaseVisible = false
    },
    async showDialogAddDatabase(business) {
      this.dialogAddDatabaseVisible = true
      await this.getAllDatabases()
      const {data: res} = await this.$axios.post('/business/get_business_info_database_by_id.action', {id: business.id})
      console.log(res)
      let temp = []
      // 设置默认选中
      res.content.result.forEach((item) => {
        temp.push(item.real_id)
      })
      // 设置禁用
      this.databaseList[0].children.forEach((item) => {
        if (temp.indexOf(item.id) !== -1) {
          item['disabled'] = true
        }
      })
      this.defKeysForDatabase = temp
      this.clickBusinessId = business.id
    },
    showAddBusinessDialog() {
      this.addBusinessDialog = true
      this.getAllHosts()
      this.getAllDatabases()
    },
    // 懒加载
    async load(tree, treeNode, resolve) {
      const {data: res} = await this.$axios.post('/business/get_business_info.action', {id: tree.id})
      // 方便后台删除，在每个设备（数据库）信息中加入 归属的业务的 id
      console.log(res)
      res.content.result.forEach((item) => {
        item['business_id'] = tree.id
      })
      tree.children = res.content.result
      console.log(tree.children)
      resolve(tree.children)
    },
    async deleteItem(tableItem) {
      console.log(tableItem)
      let message = "是否删除" + tableItem.name + "(" + tableItem.type + ")"
      const confirmRes = await this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => {
        console.log(err)
      })
      if (confirmRes !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const {data: res} = await this.$axios.post('/business/delete_business_or_relation.action', {tableItem})
      console.log(res)
      if (res.content.result === -1) {
        return this.$message.error("删除失败")
      }
      this.$message.success("删除成功")
      await this.getAllBusiness()
      const {data: result} = await this.$axios.post('/business/get_business_info.action', {id: tableItem.business_id})
      this.businessList.forEach((item) => {
        if (tableItem.business_id === item.id) {
          item.children = result.content.result
          console.log("s")
        }
      })
      // 刷新页面
      this.reload()
    },
    async addHost() {
      const keys = [
        ...this.$refs.treeRefForHost.getCheckedKeys().filter(item => item !== 0)
        // ...this.$refs.treeRefForHost.getHalfCheckedKeys()
      ]
      // 排除默认选中的 设备
      const selected = this.defKeysForHost
      const diff = keys.filter(function (val) {
        return selected.indexOf(val) === -1
      })
      const {data: res} = await this.$axios.post('/business/add_business_host_relation.action', {
        id: this.clickBusinessId,
        hostList: diff
      })
      if (res.content.result < 0) {
        this.$message.error("添加设备失败")
      }
      this.$message.success("添加设备成功")
      this.dialogAddHostVisible = false
      this.reload()
    },
    async addDatabase() {
      const keys = [
        ...this.$refs.treeRefForDatabase.getCheckedKeys().filter(item => item !== 0)
      ]
      const selected = this.defKeysForDatabase
      const diff = keys.filter(function (val) {
        return selected.indexOf(val) === -1
      })
      const {data: res} = await this.$axios.post('/business/add_business_database_relation.action', {
        id: this.clickBusinessId,
        databaseList: diff
      })
      if (res.content.result < 0) {
        this.$message.error("添加数据库失败")
      }
      this.$message.success("添加数据库成功")
      this.dialogAddDatabaseVisible = false
      this.reload()
    }
  }
}
</script>
<style scoped>
#BusinessManagement {
  height: 100%;
  width: 100%;
  background-color: #fff;
}

.outcontainer {
  display: flex;
}

.main {
  padding: 20px;
  margin-top: 60px;
}

.tree-dialog-settings {
  background-color: #F0F2F5;
  height: 60%;
  width: 30%;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
